<template>
  <div class="p-2">
    <!-- 开放API模块 -->
    <!-- 查询表单 -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
        <el-form-item label="API名称" prop="apiName">
          <el-input
            v-model="queryParams.apiName"
            placeholder="请输入API名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="API分类" prop="category">
          <el-select v-model="queryParams.category" placeholder="请选择API分类" clearable style="width: 200px">
            <el-option label="全部" value="" />
            <el-option label="设备管理" value="device" />
            <el-option label="数据查询" value="data" />
            <el-option label="消息推送" value="message" />
            <el-option label="用户管理" value="user" />
            <el-option label="系统配置" value="system" />
          </el-select>
        </el-form-item>
        <el-form-item label="请求方式" prop="method">
          <el-select v-model="queryParams.method" placeholder="请选择请求方式" clearable style="width: 150px">
            <el-option label="全部" value="" />
            <el-option label="GET" value="GET" />
            <el-option label="POST" value="POST" />
            <el-option label="PUT" value="PUT" />
            <el-option label="DELETE" value="DELETE" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 150px">
            <el-option label="全部" value="" />
            <el-option label="启用" value="enabled" />
            <el-option label="禁用" value="disabled" />
            <el-option label="维护中" value="maintenance" />
          </el-select>
        </el-form-item>
        <el-form-item label="版本" prop="version">
          <el-select v-model="queryParams.version" placeholder="请选择版本" clearable style="width: 150px">
            <el-option label="全部" value="" />
            <el-option label="v1.0" value="v1.0" />
            <el-option label="v1.1" value="v1.1" />
            <el-option label="v2.0" value="v2.0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="10" style="margin-bottom: 8px">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-item">
            <div class="stat-value">{{ statistics.total }}</div>
            <div class="stat-label">总API数量</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-item">
            <div class="stat-value enabled">{{ statistics.enabled }}</div>
            <div class="stat-label">启用API</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-item">
            <div class="stat-value calls">{{ statistics.todayCalls }}</div>
            <div class="stat-label">今日调用</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-item">
            <div class="stat-value rate">{{ statistics.successRate }}%</div>
            <div class="stat-label">成功率</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作按钮 -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <div class="toolbar">
        <div class="toolbar-left">
          <el-button type="primary" icon="Plus" @click="handleAdd">新增API</el-button>
          <el-button type="success" icon="Document" @click="handleViewDoc">API文档</el-button>
          <el-button type="warning" icon="Key" @click="handleApiKey">API密钥</el-button>
          <el-button type="info" icon="Monitor" @click="handleMonitor">调用监控</el-button>
          <el-button type="danger" icon="Delete" @click="handleBatchDelete" :disabled="!selectedIds.length">批量删除</el-button>
        </div>
        <div class="toolbar-right">
          <el-tooltip content="密度">
            <el-dropdown trigger="click" @command="handleSizeChange">
              <el-button circle>
                <el-icon><Operation /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="large">宽松</el-dropdown-item>
                  <el-dropdown-item command="default">默认</el-dropdown-item>
                  <el-dropdown-item command="small">紧凑</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-tooltip>
        </div>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="hover">
      <el-table
        v-loading="loading"
        :data="apiList"
        :size="tableSize"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="API名称" prop="apiName" width="200" show-overflow-tooltip>
          <template #default="scope">
            <div class="api-name">
              <el-icon class="api-icon"><Link /></el-icon>
              {{ scope.row.apiName }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="API路径" prop="apiPath" width="300" show-overflow-tooltip>
          <template #default="scope">
            <el-tag :type="getMethodTagType(scope.row.method)" size="small" style="margin-right: 8px">
              {{ scope.row.method }}
            </el-tag>
            <code class="api-path">{{ scope.row.apiPath }}</code>
          </template>
        </el-table-column>
        <el-table-column label="API分类" prop="category" width="120" align="center">
          <template #default="scope">
            <el-tag :type="getCategoryTagType(scope.row.category)" size="small">
              {{ getCategoryText(scope.row.category) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="版本" prop="version" width="80" align="center">
          <template #default="scope">
            <el-tag size="small" plain>{{ scope.row.version }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)" size="small">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="调用次数" prop="callCount" width="100" align="center">
          <template #default="scope">
            <span class="call-count">{{ scope.row.callCount.toLocaleString() }}</span>
          </template>
        </el-table-column>
        <el-table-column label="成功率" prop="successRate" width="100" align="center">
          <template #default="scope">
            <el-progress
              :percentage="scope.row.successRate"
              :stroke-width="8"
              :show-text="false"
              :status="scope.row.successRate >= 95 ? 'success' : scope.row.successRate >= 80 ? 'warning' : 'exception'"
            />
            <div class="rate-text">{{ scope.row.successRate }}%</div>
          </template>
        </el-table-column>
        <el-table-column label="权限级别" prop="authLevel" width="120" align="center">
          <template #default="scope">
            <el-tag :type="getAuthLevelTagType(scope.row.authLevel)" size="small">
              {{ getAuthLevelText(scope.row.authLevel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="160" align="center" />
        <el-table-column label="更新时间" prop="updateTime" width="160" align="center" />
        <el-table-column label="操作" width="280" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="info" size="small" @click="handleViewDetail(scope.row)">详情</el-button>
            <el-button type="success" size="small" @click="handleTest(scope.row)">测试</el-button>
            <el-button 
              :type="scope.row.status === 'enabled' ? 'warning' : 'success'" 
              size="small" 
              @click="handleToggleStatus(scope.row)"
            >
              {{ scope.row.status === 'enabled' ? '禁用' : '启用' }}
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :small="false"
          :disabled="loading"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handlePageSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑API对话框 -->
    <el-dialog :title="form.apiId ? '编辑API' : '新增API'" v-model="formDialog.visible" width="800px" append-to-body>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="API名称" prop="apiName">
              <el-input v-model="form.apiName" placeholder="请输入API名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="API分类" prop="category">
              <el-select v-model="form.category" placeholder="请选择API分类" style="width: 100%">
                <el-option label="设备管理" value="device" />
                <el-option label="数据查询" value="data" />
                <el-option label="消息推送" value="message" />
                <el-option label="用户管理" value="user" />
                <el-option label="系统配置" value="system" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="请求方式" prop="method">
              <el-select v-model="form.method" placeholder="请选择请求方式" style="width: 100%">
                <el-option label="GET" value="GET" />
                <el-option label="POST" value="POST" />
                <el-option label="PUT" value="PUT" />
                <el-option label="DELETE" value="DELETE" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="版本" prop="version">
              <el-select v-model="form.version" placeholder="请选择版本" style="width: 100%">
                <el-option label="v1.0" value="v1.0" />
                <el-option label="v1.1" value="v1.1" />
                <el-option label="v2.0" value="v2.0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="权限级别" prop="authLevel">
              <el-select v-model="form.authLevel" placeholder="请选择权限级别" style="width: 100%">
                <el-option label="公开" value="public" />
                <el-option label="认证" value="auth" />
                <el-option label="管理员" value="admin" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="API路径" prop="apiPath">
          <el-input v-model="form.apiPath" placeholder="请输入API路径，如：/api/v1/devices" />
        </el-form-item>
        <el-form-item label="API描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入API描述" />
        </el-form-item>
        <el-form-item label="请求参数">
          <el-input v-model="form.requestParams" type="textarea" :rows="4" placeholder="请输入请求参数JSON格式" />
        </el-form-item>
        <el-form-item label="响应示例">
          <el-input v-model="form.responseExample" type="textarea" :rows="4" placeholder="请输入响应示例JSON格式" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio label="enabled">启用</el-radio>
                <el-radio label="disabled">禁用</el-radio>
                <el-radio label="maintenance">维护中</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="限流配置">
              <el-input-number v-model="form.rateLimit" :min="0" :max="10000" placeholder="每分钟调用次数" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="formDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- API详情对话框 -->
    <el-dialog title="API详情" v-model="detailDialog.visible" width="900px" append-to-body>
      <el-tabs v-model="activeTab">
        <el-tab-pane label="基本信息" name="basic">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="API名称">{{ detailData.apiName }}</el-descriptions-item>
            <el-descriptions-item label="API分类">{{ getCategoryText(detailData.category) }}</el-descriptions-item>
            <el-descriptions-item label="请求方式">{{ detailData.method }}</el-descriptions-item>
            <el-descriptions-item label="版本">{{ detailData.version }}</el-descriptions-item>
            <el-descriptions-item label="API路径" :span="2">{{ detailData.apiPath }}</el-descriptions-item>
            <el-descriptions-item label="状态">{{ getStatusText(detailData.status) }}</el-descriptions-item>
            <el-descriptions-item label="权限级别">{{ getAuthLevelText(detailData.authLevel) }}</el-descriptions-item>
            <el-descriptions-item label="调用次数">{{ detailData.callCount?.toLocaleString() }}</el-descriptions-item>
            <el-descriptions-item label="成功率">{{ detailData.successRate }}%</el-descriptions-item>
            <el-descriptions-item label="限流配置">{{ detailData.rateLimit }}/分钟</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ detailData.createTime }}</el-descriptions-item>
            <el-descriptions-item label="API描述" :span="2">{{ detailData.description }}</el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
        <el-tab-pane label="请求参数" name="request">
          <pre class="json-content">{{ detailData.requestParams }}</pre>
        </el-tab-pane>
        <el-tab-pane label="响应示例" name="response">
          <pre class="json-content">{{ detailData.responseExample }}</pre>
        </el-tab-pane>
        <el-tab-pane label="调用统计" name="statistics">
          <div class="stats-container">
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="stat-box">
                  <div class="stat-title">今日调用</div>
                  <div class="stat-number">{{ detailData.todayCount || 0 }}</div>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="stat-box">
                  <div class="stat-title">本周调用</div>
                  <div class="stat-number">{{ detailData.weekCount || 0 }}</div>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="stat-box">
                  <div class="stat-title">本月调用</div>
                  <div class="stat-number">{{ detailData.monthCount || 0 }}</div>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <!-- API测试对话框 -->
    <el-dialog title="API测试" v-model="testDialog.visible" width="800px" append-to-body>
      <div class="test-container">
        <div class="test-header">
          <el-tag :type="getMethodTagType(testData.method)" size="large">{{ testData.method }}</el-tag>
          <span class="test-url">{{ testData.apiPath }}</span>
        </div>
        
        <el-form :model="testForm" label-width="100px">
          <el-form-item label="请求头">
            <el-input v-model="testForm.headers" type="textarea" :rows="3" placeholder="请输入请求头JSON格式" />
          </el-form-item>
          <el-form-item label="请求参数" v-if="testData.method !== 'GET'">
            <el-input v-model="testForm.body" type="textarea" :rows="5" placeholder="请输入请求参数JSON格式" />
          </el-form-item>
          <el-form-item label="查询参数" v-if="testData.method === 'GET'">
            <el-input v-model="testForm.query" placeholder="请输入查询参数，如：id=1&name=test" />
          </el-form-item>
        </el-form>
        
        <div class="test-actions">
          <el-button type="primary" @click="handleSendTest" :loading="testLoading">发送请求</el-button>
          <el-button @click="handleClearTest">清空</el-button>
        </div>
        
        <div class="test-response" v-if="testResponse">
          <h4>响应结果</h4>
          <div class="response-status">
            <el-tag :type="testResponse.status >= 200 && testResponse.status < 300 ? 'success' : 'danger'">
              {{ testResponse.status }} {{ testResponse.statusText }}
            </el-tag>
            <span class="response-time">{{ testResponse.time }}ms</span>
          </div>
          <pre class="response-content">{{ testResponse.data }}</pre>
        </div>
      </div>
    </el-dialog>

    <!-- API密钥管理对话框 -->
    <el-dialog title="API密钥管理" v-model="keyDialog.visible" width="700px" append-to-body>
      <div class="key-container">
        <div class="key-header">
          <el-button type="primary" @click="handleGenerateKey">生成新密钥</el-button>
          <el-button type="warning" @click="handleRefreshKey">刷新密钥</el-button>
        </div>
        
        <el-table :data="apiKeys" style="width: 100%; margin-top: 20px">
          <el-table-column label="密钥名称" prop="keyName" />
          <el-table-column label="密钥值" prop="keyValue" show-overflow-tooltip>
            <template #default="scope">
              <code class="api-key">{{ scope.row.keyValue }}</code>
              <el-button type="text" size="small" @click="handleCopyKey(scope.row.keyValue)">复制</el-button>
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="status" width="100" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.status === 'active' ? 'success' : 'danger'" size="small">
                {{ scope.row.status === 'active' ? '激活' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="createTime" width="160" />
          <el-table-column label="操作" width="240" align="center">
            <template #default="scope">
              <el-button 
                :type="scope.row.status === 'active' ? 'warning' : 'success'" 
                size="small" 
                @click="handleToggleKeyStatus(scope.row)"
              >
                {{ scope.row.status === 'active' ? '禁用' : '启用' }}
              </el-button>
              <el-button type="danger" size="small" @click="handleDeleteKey(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="OpenApi" lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Document, Key, Monitor, Delete, Operation, Link } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const tableSize = ref('default')
const selectedIds = ref([])
const total = ref(0)
const activeTab = ref('basic')
const testLoading = ref(false)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 20,
  apiName: '',
  category: '',
  method: '',
  status: '',
  version: ''
})

// 统计数据
const statistics = reactive({
  total: 156,
  enabled: 142,
  todayCalls: 25680,
  successRate: 98.5
})

// API列表
const apiList = ref([
  {
    apiId: 'API001',
    apiName: '获取设备列表',
    apiPath: '/api/v1/devices',
    category: 'device',
    method: 'GET',
    version: 'v1.0',
    status: 'enabled',
    callCount: 15680,
    successRate: 99.2,
    authLevel: 'auth',
    createTime: '2024-01-10 10:30:00',
    updateTime: '2024-01-15 14:20:00',
    description: '获取设备列表信息，支持分页和筛选',
    requestParams: '{\n  "pageNum": 1,\n  "pageSize": 20,\n  "deviceType": "sensor"\n}',
    responseExample: '{\n  "code": 200,\n  "data": {\n    "list": [],\n    "total": 100\n  }\n}',
    rateLimit: 1000
  },
  {
    apiId: 'API002',
    apiName: '创建设备',
    apiPath: '/api/v1/devices',
    category: 'device',
    method: 'POST',
    version: 'v1.0',
    status: 'enabled',
    callCount: 3250,
    successRate: 97.8,
    authLevel: 'admin',
    createTime: '2024-01-10 10:35:00',
    updateTime: '2024-01-15 14:25:00',
    description: '创建新的设备信息',
    requestParams: '{\n  "deviceName": "温度传感器",\n  "deviceType": "sensor",\n  "location": "车间A"\n}',
    responseExample: '{\n  "code": 200,\n  "data": {\n    "deviceId": "DEV001"\n  }\n}',
    rateLimit: 100
  },
  {
    apiId: 'API003',
    apiName: '查询设备数据',
    apiPath: '/api/v1/data/query',
    category: 'data',
    method: 'POST',
    version: 'v1.1',
    status: 'enabled',
    callCount: 45680,
    successRate: 98.9,
    authLevel: 'auth',
    createTime: '2024-01-10 11:00:00',
    updateTime: '2024-01-15 15:00:00',
    description: '查询设备历史数据',
    requestParams: '{\n  "deviceId": "DEV001",\n  "startTime": "2024-01-01",\n  "endTime": "2024-01-15"\n}',
    responseExample: '{\n  "code": 200,\n  "data": {\n    "records": []\n  }\n}',
    rateLimit: 500
  },
  {
    apiId: 'API004',
    apiName: '发送消息',
    apiPath: '/api/v1/message/send',
    category: 'message',
    method: 'POST',
    version: 'v2.0',
    status: 'maintenance',
    callCount: 8920,
    successRate: 95.5,
    authLevel: 'admin',
    createTime: '2024-01-10 11:30:00',
    updateTime: '2024-01-15 16:00:00',
    description: '向设备发送控制消息',
    requestParams: '{\n  "deviceId": "DEV001",\n  "message": "turn_on",\n  "priority": "high"\n}',
    responseExample: '{\n  "code": 200,\n  "data": {\n    "messageId": "MSG001"\n  }\n}',
    rateLimit: 200
  },
  {
    apiId: 'API005',
    apiName: '用户认证',
    apiPath: '/api/v1/auth/login',
    category: 'user',
    method: 'POST',
    version: 'v1.0',
    status: 'disabled',
    callCount: 12450,
    successRate: 99.8,
    authLevel: 'public',
    createTime: '2024-01-10 12:00:00',
    updateTime: '2024-01-15 16:30:00',
    description: '用户登录认证接口',
    requestParams: '{\n  "username": "admin",\n  "password": "123456"\n}',
    responseExample: '{\n  "code": 200,\n  "data": {\n    "token": "eyJhbGciOiJIUzI1NiJ9..."\n  }\n}',
    rateLimit: 60
  }
])

// 表单数据
const form = reactive({
  apiId: '',
  apiName: '',
  apiPath: '',
  category: '',
  method: '',
  version: '',
  status: 'enabled',
  authLevel: 'auth',
  description: '',
  requestParams: '',
  responseExample: '',
  rateLimit: 1000
})

// 表单验证规则
const rules = {
  apiName: [{ required: true, message: '请输入API名称', trigger: 'blur' }],
  apiPath: [{ required: true, message: '请输入API路径', trigger: 'blur' }],
  category: [{ required: true, message: '请选择API分类', trigger: 'change' }],
  method: [{ required: true, message: '请选择请求方式', trigger: 'change' }],
  version: [{ required: true, message: '请选择版本', trigger: 'change' }],
  authLevel: [{ required: true, message: '请选择权限级别', trigger: 'change' }]
}

// 对话框数据
const formDialog = reactive({ visible: false })
const detailDialog = reactive({ visible: false })
const testDialog = reactive({ visible: false })
const keyDialog = reactive({ visible: false })

const detailData = reactive({})
const testData = reactive({})
const testForm = reactive({
  headers: '{\n  "Content-Type": "application/json",\n  "Authorization": "Bearer your-token"\n}',
  body: '',
  query: ''
})
const testResponse = ref(null)

// API密钥数据
const apiKeys = ref([
  {
    keyId: 'KEY001',
    keyName: '默认密钥',
    keyValue: 'ak_1234567890abcdef1234567890abcdef',
    status: 'active',
    createTime: '2024-01-10 10:00:00'
  },
  {
    keyId: 'KEY002',
    keyName: '测试密钥',
    keyValue: 'ak_abcdef1234567890abcdef1234567890',
    status: 'disabled',
    createTime: '2024-01-12 15:30:00'
  }
])

// 获取分类文本
const getCategoryText = (category: string) => {
  const categoryMap = {
    device: '设备管理',
    data: '数据查询',
    message: '消息推送',
    user: '用户管理',
    system: '系统配置'
  }
  return categoryMap[category] || category
}

// 获取分类标签类型
const getCategoryTagType = (category: string) => {
  const categoryMap = {
    device: 'primary',
    data: 'success',
    message: 'warning',
    user: 'info',
    system: 'danger'
  }
  return categoryMap[category] || ''
}

// 获取请求方式标签类型
const getMethodTagType = (method: string) => {
  const methodMap = {
    GET: 'success',
    POST: 'primary',
    PUT: 'warning',
    DELETE: 'danger'
  }
  return methodMap[method] || ''
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap = {
    enabled: '启用',
    disabled: '禁用',
    maintenance: '维护中'
  }
  return statusMap[status] || status
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const statusMap = {
    enabled: 'success',
    disabled: 'danger',
    maintenance: 'warning'
  }
  return statusMap[status] || ''
}

// 获取权限级别文本
const getAuthLevelText = (authLevel: string) => {
  const authMap = {
    public: '公开',
    auth: '认证',
    admin: '管理员'
  }
  return authMap[authLevel] || authLevel
}

// 获取权限级别标签类型
const getAuthLevelTagType = (authLevel: string) => {
  const authMap = {
    public: 'info',
    auth: 'warning',
    admin: 'danger'
  }
  return authMap[authLevel] || ''
}

// 查询
const handleQuery = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
    ElMessage.success('查询完成')
  }, 1000)
}

// 重置查询
const resetQuery = () => {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 20,
    apiName: '',
    category: '',
    method: '',
    status: '',
    version: ''
  })
  handleQuery()
}

// 新增API
const handleAdd = () => {
  Object.assign(form, {
    apiId: '',
    apiName: '',
    apiPath: '',
    category: '',
    method: '',
    version: '',
    status: 'enabled',
    authLevel: 'auth',
    description: '',
    requestParams: '',
    responseExample: '',
    rateLimit: 1000
  })
  formDialog.visible = true
}

// 编辑API
const handleEdit = (row: any) => {
  Object.assign(form, { ...row })
  formDialog.visible = true
}

// 提交表单
const handleSubmit = () => {
  ElMessage.success(form.apiId ? '编辑成功' : '新增成功')
  formDialog.visible = false
}

// 查看详情
const handleViewDetail = (row: any) => {
  Object.assign(detailData, { ...row })
  detailDialog.visible = true
}

// 测试API
const handleTest = (row: any) => {
  Object.assign(testData, { ...row })
  testForm.body = row.requestParams
  testResponse.value = null
  testDialog.visible = true
}

// 发送测试请求
const handleSendTest = () => {
  testLoading.value = true
  setTimeout(() => {
    testResponse.value = {
      status: 200,
      statusText: 'OK',
      time: 156,
      data: testData.responseExample
    }
    testLoading.value = false
    ElMessage.success('请求发送成功')
  }, 1000)
}

// 清空测试
const handleClearTest = () => {
  testForm.body = ''
  testForm.query = ''
  testResponse.value = null
}

// 切换状态
const handleToggleStatus = (row: any) => {
  const newStatus = row.status === 'enabled' ? 'disabled' : 'enabled'
  ElMessage.success(`API已${newStatus === 'enabled' ? '启用' : '禁用'}`)
}

// 删除API
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确认删除API "${row.apiName}"？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
  })
}

// 批量删除
const handleBatchDelete = () => {
  ElMessageBox.confirm(`确认删除选中的${selectedIds.value.length}个API？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
    selectedIds.value = []
  })
}

// 查看API文档
const handleViewDoc = () => {
  ElMessage.info('跳转到API文档页面')
}

// API密钥管理
const handleApiKey = () => {
  keyDialog.visible = true
}

// 调用监控
const handleMonitor = () => {
  ElMessage.info('跳转到调用监控页面')
}

// 生成新密钥
const handleGenerateKey = () => {
  const newKey = {
    keyId: 'KEY' + Date.now(),
    keyName: '新密钥',
    keyValue: 'ak_' + Math.random().toString(36).substr(2, 32),
    status: 'active',
    createTime: new Date().toLocaleString()
  }
  apiKeys.value.push(newKey)
  ElMessage.success('密钥生成成功')
}

// 刷新密钥
const handleRefreshKey = () => {
  ElMessage.success('密钥已刷新')
}

// 复制密钥
const handleCopyKey = (keyValue: string) => {
  navigator.clipboard.writeText(keyValue)
  ElMessage.success('密钥已复制到剪贴板')
}

// 切换密钥状态
const handleToggleKeyStatus = (row: any) => {
  row.status = row.status === 'active' ? 'disabled' : 'active'
  ElMessage.success(`密钥已${row.status === 'active' ? '启用' : '禁用'}`)
}

// 删除密钥
const handleDeleteKey = (row: any) => {
  ElMessageBox.confirm(`确认删除密钥 "${row.keyName}"？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const index = apiKeys.value.findIndex(item => item.keyId === row.keyId)
    if (index > -1) {
      apiKeys.value.splice(index, 1)
    }
    ElMessage.success('删除成功')
  })
}

// 表格大小变化
const handleSizeChange = (size: string) => {
  tableSize.value = size
}

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedIds.value = selection.map(item => item.apiId)
}

// 分页大小变化
const handlePageSizeChange = (size: number) => {
  queryParams.pageSize = size
  handleQuery()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  queryParams.pageNum = page
  handleQuery()
}

// 组件挂载
onMounted(() => {
  handleQuery()
  total.value = apiList.value.length
})
</script>

<style scoped>
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.toolbar-left {
  display: flex;
  gap: 10px;
}

.toolbar-right {
  display: flex;
  gap: 10px;
}

.stat-card {
  text-align: center;
}

.stat-item {
  padding: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-value.enabled {
  color: #67c23a;
}

.stat-value.calls {
  color: #409eff;
}

.stat-value.rate {
  color: #e6a23c;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.api-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.api-icon {
  color: #409eff;
}

.api-path {
  background-color: #f5f7fa;
  padding: 2px 6px;
  border-radius: 3px;
  font-family: 'Courier New', monospace;
  font-size: 12px;
}

.call-count {
  font-weight: bold;
  color: #409eff;
}

.rate-text {
  font-size: 12px;
  color: #606266;
  margin-top: 2px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.json-content {
  background-color: #f5f7fa;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 15px;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  line-height: 1.5;
  color: #303133;
  white-space: pre-wrap;
  word-wrap: break-word;
  max-height: 300px;
  overflow-y: auto;
}

.stats-container {
  margin-top: 20px;
}

.stat-box {
  text-align: center;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.stat-title {
  font-size: 14px;
  color: #6c757d;
  margin-bottom: 10px;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #495057;
}

.test-container {
  padding: 20px 0;
}

.test-header {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.test-url {
  font-family: 'Courier New', monospace;
  font-size: 14px;
  color: #303133;
  background-color: #f5f7fa;
  padding: 5px 10px;
  border-radius: 4px;
}

.test-actions {
  margin: 20px 0;
  text-align: center;
}

.test-response {
  margin-top: 30px;
}

.test-response h4 {
  margin-bottom: 15px;
  color: #303133;
}

.response-status {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 15px;
}

.response-time {
  font-size: 12px;
  color: #909399;
}

.response-content {
  background-color: #f5f7fa;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 15px;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  line-height: 1.5;
  color: #303133;
  white-space: pre-wrap;
  word-wrap: break-word;
  max-height: 400px;
  overflow-y: auto;
}

.key-container {
  padding: 20px 0;
}

.key-header {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.api-key {
  background-color: #f5f7fa;
  padding: 2px 6px;
  border-radius: 3px;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  margin-right: 10px;
}

.dialog-footer {
  text-align: right;
}
</style>